# -*- coding: utf-8 -*-
from collections import OrderedDict

from django.core import paginator
from django.core.paginator import Paginator as DjangoPaginator
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from django.core.paginator import InvalidPage


class CustomPagination(PageNumberPagination):
    page_size = 20
    page_query_param = 'page'  # 默认就是'page'，如果你用别的名字要改成对应的
    page_size_query_param = "pageSize"
    max_page_size = 999
    django_paginator_class = DjangoPaginator

    def paginate_queryset(self, queryset, request, view=None):
        """
        重写paginate_queryset让分页超过正常分页:有原来的4000错误无效页面。改写为返回2000成功，data=[]提示
        """
        # 初始化必要的属性，确保即使出现异常也能安全访问
        self.paginator = None
        self.page = None
        self.request = request
        
        try:
            page_size = self.get_page_size(request)
            if not page_size:
                return None
            
            # 保存paginator实例，确保即使出现异常也能访问
            paginator = self.django_paginator_class(queryset, page_size)
            self.paginator = paginator
            
            page_number = self.get_page_number(request, paginator)
            self.page = paginator.page(page_number)
            
            if paginator.num_pages > 1 and self.template is not None:
                # The browsable API should display pagination controls.
                self.display_page_controls = True
            
            # 安全地返回页面数据
            return list(self.page) if self.page else []
        except InvalidPage as exc:
            # 处理无效页面异常，返回空列表
            return []
        except Exception:
            # 捕获所有其他异常，确保不会导致500错误
            return []

    def get_paginated_response(self, data):
        """
        生成带分页信息的响应
        """
        code = 0
        msg = 'ok'
        total = 0
        
        # 使用try-except包装整个逻辑，确保不会抛出异常
        try:
            # 计算总记录数，采用安全的方式获取总数
            if hasattr(self, 'paginator') and self.paginator is not None:
                total = self.paginator.count
            elif hasattr(self, 'page') and self.page is not None:
                if hasattr(self.page, 'paginator'):
                    total = self.page.paginator.count
        except Exception:
            # 捕获所有可能的异常，确保响应正常返回
            total = 0
        
        # 构建响应数据
        res = {
            "total": total,
            "items": data if data is not None else []
        }
        
        # 如果没有数据，保持响应格式一致
        if not data:
            msg = "暂无数据"
        
        # 返回格式化的响应
        return Response({
            'code': code,
            'message': msg,
            'data': res,
            'error': None
        })
